package com.bit.ThreadTest;

import java.util.concurrent.PriorityBlockingQueue;

public class Test13 {
    //用来描述任务
    static class Task implements Comparable<Task>{
        private Runnable command;
        //是一个时间戳
        private long time;
        public Task(Runnable command,long time){
            this.command = command;
            this.time = System.currentTimeMillis()+time;
        }
        public void run(){
            command.run();
        }

        @Override
        public int compareTo(Task o) {
            return (int)(this.time - o.time);
        }
    }
    //Timer类中内涵schedule方法

    static class Timer{
        private PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>();
        private Object locker = new Object();
        public void schedule(Runnable command,long delay){
            Task task = new Task(command,delay);
            queue.put(task);
            synchronized (locker){
                locker.notify();
            }
        }
        public Timer(){
            //构造一个线程来不断地扫描对头，来判断是否要开始
            Thread t = new Thread(){
                @Override
                public void run() {
                    while(true){
                        //取出队首元素来判断是否到时间了
                        try {
                            Task task = queue.take();
                            long current = System.currentTimeMillis();
                            if (current < task.time){
                                //时间还没到,就等待
                                queue.put(task);
                                synchronized (locker){
                                    locker.wait(task.time-current);
                                }
                            }else{
                                task.run();
                            }
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                                break;
                            }
                        }
                    }
                };
            t.start();
            }
        }

    public static void main(String[] args) {
        System.out.println("程序启动");
        Timer timer = new Timer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("定时器启动");
            }
        },3000);
    }
}
